﻿using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using myOSity.API;
using XamlaApp.Model;
using XamlaApp.Resources;
using myOSity.API.Interop;

namespace XamlaApp
{
    public class MyOSityImplementation : ImoApplication, ImoInteropApplication
    {
        private MoRuntimeAPI _api;
        private Guid _win;
        private XamlaMainPage _app;
        internal const string ImageViewerInteropName = "imageviewer.applications.myosity";
        internal const string InteropName = "xamla.applications.myosity";


        #region ImoApplication Members

        public void ApplicationEnd()
        {
            //static Unity container should be reinitialized on application exit, because subsequent load of the application in myOSity will
            //reference the same objects
            Container.InitContainer();
        }

        public string ApplicationName
        {
            get { return "Xamla"; }
        }

        public UserControl ApplicationStart(MoRuntimeAPI runtimeAPI, Guid mainWindowHandle)
        {
            _api = runtimeAPI;
            _win = mainWindowHandle;
            _app = Container.AppContainer.Resolve<XamlaMainPage>();
            _api.SetWindowWidth(_win, 800);
            _api.SetWindowHeight(_win, 600);
            _api.SetWindowAllowScrollbars(_win, false);
            _api.SetAllowWindowPerspective(_win, false);
            _api.WindowSizeChanged += ApiWindowSizeChanged;

            //because we are using a persistant container, we need to initialize objects on each run
            //myOSity apps are sometimes cached by the browser...
            var model = Container.AppContainer.Resolve<XamlaModel>();
            model.InitializeApplication();
            
            //expose the main window id to the model
            model.MoWindowID = _win;

            //expose api to the model
            model.MoApi = _api;
            _app.Loaded += AppLoaded;
            return _app;
        }

        void AppLoaded(object sender, RoutedEventArgs e)
        {
            if (_api.IsInteropProcessActive(ImageViewerInteropName))
            {
                var model = Container.AppContainer.Resolve<XamlaModel>();
                model.VM.ImageViewerAvailable = true;
            }
            if (!_api.HasFileData) return;
            LoadProject(_api.FileData);
        }

        void ApiWindowSizeChanged(object sender, MoSizeChangedEventArgs e)
        {
            if (e.WindowID.Equals(_win))
            {
                _app.Width = e.NewWidth;
                _app.Height = e.NewHeight;
            }
        }

        public ResourceDictionary Resources
        {
            get
            {
                //Getting the resource from a UserControl instance, instead of App, so we can still work locally
                //and at the same time, expose resources to myosity.
                //bad things happen in silverlight if you attempt to reference another Application class...
                return new ResourcesUserControl().Resources;
            }
        }

        public void NewInstanceRequested(MoNewInstanceRequestEventArgs args)
        {
            if (!args.HasFileData) return;
            LoadProject(args.FileData);
        }

        #endregion
        
        private static void LoadProject(Stream fileStream)
        {
            var model = Container.AppContainer.Resolve<XamlaModel>();
            model.LoadProject(fileStream);
            fileStream.Close();
        }

        #region ImoInteropApplication Members

        public string InteropID
        {
            get { return InteropName; }
        }

        public void ProcessInteropMessage(IMoInteropMessage message)
        {
            //only supporting interop from the image viewer application
            if (message.MessageFrom != ImageViewerInteropName) return;

            var model = Container.AppContainer.Resolve<XamlaModel>();
            switch(message.MessageType)
            {
                case "hello":
                    model.VM.ImageViewerAvailable = true;
                    break;
                case "goodbye":
                    model.VM.ImageViewerAvailable = false;
                    break;
            }
        }

        #endregion
    }
}
